package com.zst.amqp;

import com.zst.amqp.entity.MessageDTO;
import com.zst.amqp.entity.ConsumerInfo;
import com.zst.amqp.entity.ConsumerInfoContext;
import com.zst.amqp.utils.ConsumerInvokeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

import java.util.List;

/**
 * 消息分发
 *
 * @author zst
 */
public class MessageDispatcher {
    private static final Logger logger = LoggerFactory.getLogger(MessageDispatcher.class);

    private ConsumerInfoContext consumerInfoContext;
    private ApplicationContext applicationContext;

    public MessageDispatcher(ConsumerInfoContext consumerInfoContext, ApplicationContext applicationContext) {
        this.consumerInfoContext = consumerInfoContext;
        this.applicationContext = applicationContext;
    }

    /**
     * 把收到的消息分发给各个消费者，忽略消费者抛出的异常
     * @param messageDTO
     */
    public void dispatch(MessageDTO messageDTO) throws Exception {
        List<ConsumerInfo> consumerInfoList = consumerInfoContext.getConsumerInfoList(messageDTO.getRoutingKey());
        if (consumerInfoList == null) {
            return;
        }

        for (ConsumerInfo consumerInfo : consumerInfoList) {
            try {
                ConsumerInvokeUtils.invoke(applicationContext, consumerInfo, messageDTO);
            } catch (Exception e) {
                throw new Exception("Catch Exception while dispatching message", e);
            }
        }
    }
}
